package com.itlong.cloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int core = Runtime.getRuntime().availableProcessors();//CPU个数
        executor.setCorePoolSize(core);//核心池大小
        executor.setMaxPoolSize(core * 2 + 1);//线程池最大线程个数
        executor.setKeepAliveSeconds(60);//线程的保活时间，单位秒
        executor.setQueueCapacity(50);//缓存队列的个数
        executor.setThreadNamePrefix("async-");//名称前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

}